﻿using System.Collections.Generic;
using System.Linq;
using pbvs.Data;
using pbvs.Models;
using pbvs.Utilities;

namespace pbvs.Admin
{
    public class PbvsUserRepository
    {
        private readonly PbvsContext _db;

        public PbvsUserRepository()
        {
            this._db = new PbvsContext();
        }

        public bool ValidateUser(string username, string password)
        {
            return _db.Logins.Any(l => l.Email == username && l.Password == password); //BCrypt.CheckPassword(password, l.Password));
        }

        public void CreateUser(Client client)
        {
            _db.Clients.Add(client);
            Save();
        }

        public PbvsUser GetUser(string username)
        {
            return new PbvsUser(_db.Logins.SingleOrDefault(l => l.Email.ToLower() == username.ToLower()));
        }

        public IList<Role> GetAllRolesForUser(string username)
        {
            return _db.Logins.Single(l => l.Email.ToLower() == username.ToLower()).Roles.ToList();
        }

        public void Save()
        {
            _db.SaveChanges();
        }

        public Role GetRole(string roleName)
        {
            return _db.Roles.SingleOrDefault(r => r.Name.ToLower() == roleName.ToLower());
        }

        public void AddRoleToUser(string username, string roleName)
        {
            if (UserExists(username) && RoleExists(roleName))
            {
                _db.Logins.Single(l => l.Email.ToLower() == username.ToLower())
                  .Roles.Add(_db.Roles.Single(r => r.Name.ToLower() == roleName.ToLower()));
            }
        }

        public bool UserExists(string username)
        {
            return _db.Logins.Any(l => l.Email.ToLower() == username.ToLower());
        }

        public bool RoleExists(string roleName)
        {
            return _db.Roles.Any(r => r.Name.ToLower() == roleName.ToLower());
        }

        public void UpdatePassword(string username, string password)
        {
            _db.Logins.Single(l => l.Email.ToLower() == username.ToLower()).Password = password;
        }

        public IList<Role> GetAllRoles()
        {
            return _db.Roles.ToList();
        }
    }
}